package raceReservationServer.raceServerGateway;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.omg.CORBA.*;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import corbaServer.corba.ICorbaServer;
import corbaServer.corba.ICorbaServerHelper;
import corbaServer.corba.RaceDTO;

public class CorbaRaceServerGateway implements IRaceServerGateway 
{
	private String url = null;
	private String serverIP = null;
	private String serverName = null;
	private String serverPort = null;
	
	public CorbaRaceServerGateway(String serviceUri) 
	{
		this.url = serviceUri;
		StringTokenizer tokens = new StringTokenizer(url);
			serverIP = tokens.nextToken();
			serverPort = tokens.nextToken();	
			serverName = tokens.nextToken();
	}

	public List<RaceDO> getRaces() {
		System.out.println("getRaces Corbaaaa");
		List<RaceDO> result = new ArrayList<RaceDO>();
		RaceDTO[] racesList = null;
		
		try
		{
			
			String[] orb_args = {"-ORBInitialHost", serverIP, "-ORBInitialPort", serverPort};
			ORB orb = ORB.init(orb_args,null);
			System.out.println("ORB object created");

			org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
			System.out.println("Name service reference obtained");
			
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
			System.out.println("Generic name service reference transformed ");
			
			String name = serverName; // o args[2]
			ICorbaServer objServidor;
			objServidor = ICorbaServerHelper.narrow(ncRef.resolve_str(name));
			System.out.println("CORBA object reference obtained");
			
			racesList = objServidor.getRaces();
			System.out.println("GetRaces method called from the server");
			System.out.println(racesList.length);
			for (int i = 0; i < racesList.length; i++)
			{
				RaceDO race = new RaceDO(racesList[i].name, racesList[i].distance, racesList[i].date, racesList[i].places);
				System.out.println(race.getName());
				result.add(race);
			}
		}
		catch (InvalidName e){e.printStackTrace();}
		catch (NotFound e) {e.printStackTrace();}
		catch (CannotProceed e) {e.printStackTrace();}
		catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {e.printStackTrace();}
		
		return result;
	}

	@Override
	public String getServer() 
	{
		return serverName;
	}
	
}
